import React, { Component } from 'react'
import styles from './index.less'
import { connect } from 'dva';
import { Tree, Input, Tooltip, Icon, Dropdown, Menu, Upload, message, Button } from 'antd';
import { personalTelBookDownloadUrl, telBookUploadUrl, TelBookDownloadUrl } from '@/utils/settings.js'
import { getData } from '@/utils/localData.js'
import TelNode from './TelNode.js'
const { TreeNode } = Tree;
const Search = Input.Search;

export default class TelBookGroup extends Component {

    constructor(props) {
        super(props);
        this.state = {
            nameKey: false, //搜索节点框的值
            expandedKeys: [], //tree 显示节点key集合
            autoExpandParent: true, //是否自动展开父节点
            telList: [], //拷贝用的treeData
            maxLevel: 0, //最深节点等级
            fileList:[] //上传文件集合
        };
    }

    //树节点展开触发
    onExpand = (expandedKeys) => {
        this.setState({
          expandedKeys,
          autoExpandParent: false,
        });
    }
    //绘制树节点
    renderTreeNodes = data => data.map((item) => {
        if (item.children) {
          return (
            <TreeNode title={<TelNode dispatch = {this.props.dispatch} nameKey={this.state.nameKey} tnode = {item}/>} key={item.id} dataRef={item}>
              {this.renderTreeNodes(item.children)}
            </TreeNode>
          );
        }
    return (
        <TreeNode {...item} title={<TelNode dispatch = {this.props.dispatch} nameKey={this.state.nameKey} tnode = {item}/>} key={item.id} dataRef={item} />
        );
    })

    //搜索框回调
    onSearch = (value) => {
        this.state.expandedKeys = []
        this.state.nameKey = value
        const {telBookList} = this.props
        //数组拷贝
        this.state.telList = JSON.parse(JSON.stringify(telBookList))
        //获取关键字的最深节点层级
        this.recursionTelBookMax(this.state.telList)
        //标记带有关键字的整条分支（循环最大层级数）
        for(let i = 0;i < this.state.maxLevel; i++){
            this.recursionTelBookHasNode(this.state.telList)
        }
        //设置自动展开 （触发页面渲染）
        this.setState({
            autoExpandParent: true
        })
    }

    addTelGroup = (value) => {
        const { dispatch } = this.props
        if(value !== ''){
            dispatch({
                type: 'telBook/fetchAddTelBookGroup',
                payload: {
                    name: value,
                    glevel:1,
                    type:1
                }
            })
        }else{
            dispatch({
                type: 'telBook/addTelGroupInpShow',
                payload: {addShow: false}
            })
        }
    }

    //过滤所有show的节点
    telBookListFilter = (telList) => {
        if(this.state.nameKey){
            let list = telList.filter((item)=>{
                return item.show
            })
            this.recursionTelBook(list)//递归所有节点
            return list
        }else{
            const {telBookList} = this.props
            return telBookList
        }
    }

    //递归过滤所有show的节点
    recursionTelBook = (list) =>{
        list.forEach(element => {
            if(element.children && element.children.length > 0){
                let c = element.children.filter(item =>{
                    return item.show
                })
                element.children = c
                this.recursionTelBook(element.children)
            }
        })
    }

    //查找最深的节点级数 用于遍历更改show属性
    recursionTelBookMax = (list) => {
        list.forEach(element => {
            if(element.name.indexOf(this.state.nameKey) !== -1){
                //把包含关键字的节点的id加入tree展开数组
                this.expandedKeysAdd(element.id)
                //查找最深节点
                if(element.glevel && (element.glevel > this.state.maxLevel)){
                    this.state.maxLevel = element.glevel
                    //console.log("最大级数修改",element,this.state.nameKey)
                }
            }
            if(element.children && element.children.length > 0){
                this.recursionTelBookMax(element.children)
            }
        });
    }

    //tree展开数组添加元素去重
    expandedKeysAdd = (key) =>{
        let isSame = false
        this.state.expandedKeys.forEach(item =>{
            if(item === key){
                isSame = true
            }
        })
        if(!isSame){
            this.state.expandedKeys.push(key)
        }
    }

    //递归判断子节点包含关键字修改父节点的show属性（父节点本身包含也会修改）
    recursionTelBookHasNode = (list) =>{
        list.forEach(element => {
            //父节点本身包含关键字
            if(element.name.indexOf(this.state.nameKey) !== -1){
                element.show = true
            }
            //判断子节点数组是否包含关键字，或孙子级包含
            if(element.children && element.children.length > 0){
                let isShow = false
                element.children.forEach(item =>{
                    if(item.name.indexOf(this.state.nameKey) !== -1 || item.show){
                        isShow = true
                    }
                })
                if(isShow){
                    element.show = true
                }
                this.recursionTelBookHasNode(element.children)
            }
        });
    }



    onFileChange(info) {
        let {fileList} = info;
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
          if(info.file.response.success){
            message.success(`${info.file.name} 上传成功`);
            const { dispatch } = this.props
            dispatch({
                type: 'telBook/fetchSelLv1ByUserId',
            })
            dispatch({
                type: 'telBook/fetchSelTelBookByUserId',
                payload: {
                    page: 1
                }
            })
          }else{
            message.error(`${info.file.name} 上传失败 ， ${info.file.response.subMsg}`);
          }
          fileList = []
        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} 上传失败`);
        }
        this.setState({ fileList: fileList });
    }

    render() {
        const {addShow, dispatch} = this.props
        const {expandedKeys, autoExpandParent, telList} = this.state
        //把标记好的props的telBookList过滤到state的telList
        let list = this.telBookListFilter(telList)
        //console.log(expandedKeys,autoExpandParent)
        return (
            <div className = {styles.telBookGroup}>
                <Search style={{ marginBottom: 8 }} placeholder="查询" onSearch={this.onSearch} />
                <Tree 
                    onExpand={this.onExpand}
                    expandedKeys={expandedKeys}
                    autoExpandParent={autoExpandParent}
                    >
                    {this.renderTreeNodes(list)}
                </Tree>
                {addShow?
                <Search style={{ marginTop: 8 }} 
                    autoFocus  
                    placeholder="新增分组名" 
                    enterButton = {<Icon type="plus" />}
                    onSearch={this.addTelGroup} />
                :
                <div>
                <Tooltip title="新增分组">
                    <Icon style={{ color: '#176B2C' , marginLeft: 8, marginTop: 8}} 
                        type="plus" onClick={()=>{
                            dispatch({
                                type: 'telBook/addTelGroupInpShow',
                                payload: {addShow: true}
                            })
                        }} />
                </Tooltip>
                <Tooltip title="导出excel模板">
                    <Icon style={{ color: '#108ee9' , marginLeft: 20, marginTop: 8}} 
                        type="download" onClick={()=>{
                            window.location.href = TelBookDownloadUrl
                        }} />
                </Tooltip>
                <Tooltip title="导出excel">
                    <Icon style={{ color: '#108ee9' , marginLeft: 20, marginTop: 8}} 
                        type="download" onClick={()=>{
                            let userId = getData("userId")
                            window.location.href = personalTelBookDownloadUrl+"?userId=" + userId
                        }} />
                </Tooltip>
                <Upload 
                    fileList={this.state.fileList} 
                    action={telBookUploadUrl + "?userId=" + getData("userId")} 
                    name={"file"} 
                    onChange={this.onFileChange.bind(this)}>
                    <Tooltip title="excel导入">
                        <Icon style={{ color: '#108ee9' , marginLeft: 20, marginTop: 8}} type="upload"/>
                    </Tooltip>
                </Upload>
                </div>
                }
            </div>
        )
    }
}
